package com.argrace.smart.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.sdk.android.openaccount.OpenAccountSDK;
import com.alibaba.sdk.android.openaccount.ui.OpenAccountUIService;
import com.aliyun.alink.business.login.AlinkLoginBusiness;
import com.argrace.smart.R;
import com.argrace.smart.base.BaseFragment;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.callback.StringCallback;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.videogo.openapi.EZOpenSDK;

import org.apache.commons.codec.digest.DigestUtils;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by argrace_dev_1 on 2018/2/7.
 */

public class YingShiFragment extends BaseFragment {
    private String appKey = "5d52533ec4cd4f29a462b575927e556a";
    private String appSecret = "e862d20da299c03ba0c39f88b92c0296";
    private String Sub_accessToken = "";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_yingshi, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        init();
        super.onActivityCreated(savedInstanceState);
    }

    private void init() {
        //进入界面创建子账户
//        createAccount();
    }

    /**
     * 创建子账户
     */
    private void createAccount() {
        getAccessToken();
    }

    /**
     * 查询accesstoken
     */
    private void getAccessToken() {
        HttpParams params = new HttpParams();
        HttpHeaders headers = new HttpHeaders();
        headers.put("content-type", "application/x-www-form-urlencoded");
        params.put("appKey", appKey);
        params.put("appSecret", appSecret);
        OkGo.post("https://open.ys7.com/api/lapp/token/get").tag(getActivity()).headers(headers).params(params)
                .dialogIsShow(false)
                .tostIsShow(false)
                .cacheMode(CacheMode.NO_CACHE).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                //获取token成功去注册
                JSONObject obj = JSON.parseObject(s);
                String token = obj.getJSONObject("data").getString("accessToken");
                Log.i("info", "获取token成功" + token);
                registerAccount(token);
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                toastActBtm("token获取失败,请联系工作人员");
            }
        });
    }

    private void registerAccount(final String token) {
        HttpParams params = new HttpParams();
        HttpHeaders headers = new HttpHeaders();
        params.put("accessToken", token);
        params.put("accountName", getActivity().getSharedPreferences(ConstantConfigure.SPLOGIN_NAME, getActivity().MODE_PRIVATE).getString("mobile", "000"));
        String pwd = appKey + "#" + "123456";
        params.put("password", DigestUtils.md5Hex(pwd));
        OkGo.post("https://open.ys7.com/api/lapp/ram/account/create").tag(getActivity()).headers(headers).params(params)
                .dialogIsShow(false)
                .tostIsShow(false)
                .cacheMode(CacheMode.NO_CACHE).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.i("info", "注册账号成功" + s);
                JSONObject obj = JSON.parseObject(s);
                JSONObject obj_data = obj.getJSONObject("data");
                if (obj_data != null) {
                    String accountId = obj_data.getString("accountId");
                    getZiAccessToken(token, accountId);
                } else {
                    //注册账号成功{"code":"10034","msg":"子账号已存在"}
                    getZiAccoundId(token, getActivity().getSharedPreferences(ConstantConfigure.SPLOGIN_NAME, getActivity().MODE_PRIVATE).getString("mobile", "000"));
                    toastActBtm("账号已存在，登陆");
                }

            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                Log.i("info", "注册账号失败" + response.toString());
            }
        });
    }

    private void getZiAccoundId(final String accessToken, String accountName) {
        HttpParams params = new HttpParams();
        HttpHeaders headers = new HttpHeaders();
        params.put("accessToken", accessToken);
        params.put("accountName", accountName);
        OkGo.post("https://open.ys7.com/api/lapp/ram/account/get").tag(getActivity()).headers(headers).params(params)
                .dialogIsShow(false)
                .tostIsShow(false)
                .cacheMode(CacheMode.NO_CACHE).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.i("info", "查询子账号详细信息成功" + s);
                JSONObject obj = JSON.parseObject(s);
                JSONObject body = obj.getJSONObject("data");
                String accoundId = body.getString("accountId");
                getZiAccessToken(accessToken, accoundId);

            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                Log.i("info", "查询子账号详细信息失败" + response.toString());
            }
        });
    }

    private void getZiAccessToken(String accessToken, String accountId) {
        HttpParams params = new HttpParams();
        HttpHeaders headers = new HttpHeaders();
        params.put("accessToken", accessToken);
        params.put("accountId", accountId);
        OkGo.post("https://open.ys7.com/api/lapp/ram/token/get").tag(getActivity()).headers(headers).params(params)
                .dialogIsShow(false)
                .tostIsShow(false)
                .cacheMode(CacheMode.NO_CACHE).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.i("info", "查询子账号token成功" + s);
                JSONObject obj = JSON.parseObject(s);
                JSONObject body = obj.getJSONObject("data");
                Sub_accessToken = body.getString("accessToken");
                EZOpenSDK.getInstance().setAccessToken(Sub_accessToken);
                //查询用户设备
                getDeviceList();

            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                Log.i("info", "查询子账号token失败" + response.toString());
            }
        });
    }

    private void getDeviceList() {
        HttpParams params = new HttpParams();
        HttpHeaders headers = new HttpHeaders();
        if (Sub_accessToken == null) {
            toastActBtm("萤石的用户token为空");
            return;
        }
        params.put("accessToken", Sub_accessToken);
        OkGo.post("https://open.ys7.com/api/lapp/device/list").tag(getActivity()).headers(headers).params(params)
                .dialogIsShow(false)
                .tostIsShow(false)
                .cacheMode(CacheMode.NO_CACHE).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.i("info", "查询用户设备成功" + s);

            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                Log.i("info", "查询用户设备失败" + response.toString());
            }
        });
    }
}
